<template>
  <a-row :gutter="10">
    <a-col :md="8" :sm="24">
      <a-card :bordered="false">
        <!-- 按钮操作区域 -->
        <a-row style="margin-left: 14px;">
          <a-button @click="handleAdd(1)" type="primary">添加专题</a-button>
          <a-button @click="handleAdd(2)" type="primary">添加下级</a-button>
          <a-button @click="batchDel" type="default">删除选中</a-button>
        </a-row>
        <div style="background: #fff; padding-left: 16px; height: 100%; margin-top: 5px;">
          <a-alert type="info" :showIcon="true">
            <div slot="message">
              当前选择：<span v-if="this.currSelected.name">{{ getCurrSelectedTitle() }}</span>
              <a v-if="this.currSelected.name" style="margin-left: 10px;" @click="onClearSelected">取消选择</a>
            </div>
          </a-alert>
          <a-input-search @search="onSearch" v-model="searchValue" style="width: 95%; margin-top: 10px;" placeholder="请输入专题名称" />
          <a-icon type="sync" title="重置" :spin="loading" @click="refresh" style="width: 5%; cursor: pointer;" />
          <!-- 评价体系结构树-->
          <a-col :md="10" :sm="24" class="evaluation-system-tree">
            <template>
              <a-dropdown :trigger="[this.dropTrigger]" @visibleChange="dropStatus">
                <span style="user-select: none;">
                  <a-tree
                    checkable
                    multiple
                    :replaceFields="replaceFields"
                    :selectedKeys="selectedKeys"
                    :checkedKeys="checkedKeys"
                    :treeData="treeData"
                    :checkStrictly="checkStrictly"
                    :expandedKeys="iExpandedKeys"
                    :autoExpandParent="autoExpandParent"
                    @select="onSelect"
                    @check="onCheck"
                    @rightClick="rightHandle"
                    @expand="onExpand" />
                </span>
                <!-- 右键点击事件,和增加添加和删除功能 -->
                <a-menu slot="overlay">
                  <a-menu-item @click="handleAdd(3)" key="1">添加</a-menu-item>
                  <a-menu-item @click="handleDelete" key="2">删除</a-menu-item>
                  <a-menu-item @click="closeDrop" key="3">取消</a-menu-item>
                </a-menu>
              </a-dropdown>
            </template>
          </a-col>
        </div>
      </a-card>
      <!-- 切换父子勾选模式 -->
      <div class="drawer-bottom-button">
        <a-dropdown :trigger="['click']" placement="topCenter">
          <a-menu slot="overlay">
            <a-menu-item key="1" @click="switchCheckStrictly(1)">父子关联</a-menu-item>
            <a-menu-item key="2" @click="switchCheckStrictly(2)">取消关联</a-menu-item>
            <a-menu-item key="3" @click="checkAll">全部勾选</a-menu-item>
            <a-menu-item key="4" @click="cancelCheckAll">取消全选</a-menu-item>
            <a-menu-item key="5" @click="expandAll">展开所有</a-menu-item>
            <a-menu-item key="6" @click="closeAll">合并所有</a-menu-item>
          </a-menu>
          <a-button>
            树操作 <a-icon type="up" />
          </a-button>
        </a-dropdown>
      </div>
    </a-col>
    <a-col :md="16" :sm="24">
      <a-tabs v-model="activeKey">
        <a-tab-pane tab="基本信息" key="1" forceRender>
          <a-card :bordered="false" v-if="selectedKeys.length > 0 || addFlag == 1">
            <a-form :form="form">
              <h1 v-show="typeof(model.pid) === 'undefined' || model.pid === null" style="padding-left: 24px;">基础信息</h1>
              <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="评价分组名称">
                <a-input allow-clear placeholder="请输入分组名称" v-decorator="['name', validatorRules.name]" />
              </a-form-item>
              <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="上级分组">
                <a-tree-select
                  disabled
                  placeholder="请选择上级分组"
                  style="width: 100%;"
                  :replaceFields="selectReplaceFields"
                  :dropdownStyle="{ maxHeight: '200px', overflow: 'auto' }"
                  :treeData="treeData"
                  v-decorator="['pid', { 'initialValue' : '' }]">
                </a-tree-select>
              </a-form-item>
              <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="分组编码">
                <a-input allow-clear placeholder="请输入分组编码" v-decorator="['sysOrgCode', validatorRules.sysOrgCode]" />
              </a-form-item>
              <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="排序">
                <a-input-number allow-clear v-decorator="['sort', { 'initialValue' : 0 }]" />
              </a-form-item>
              <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="描述">
                <a-textarea allow-clear placeholder="请输入描述" v-decorator="['description', { 'initialValue' : '' }]" />
              </a-form-item>
              <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="是否启用">
                <a-radio-group v-decorator="['status', validatorRules.status]">
                  <a-radio :value="1">启用</a-radio>
                  <a-radio :value="0">停用</a-radio>
                </a-radio-group>
              </a-form-item>
              <h1 v-show="typeof(model.pid) === 'undefined' || model.pid === null" style="padding-left: 24px;">维度信息</h1>
              <a-form-item v-show="typeof(model.pid) === 'undefined' || model.pid === null" :labelCol="labelCol" :wrapperCol="wrapperCol" label="维度类型">
                <a-radio-group v-model="dimensionType" @change="dimensionTypeChange">
                  <a-radio value="0">评价周期</a-radio>
                  <a-radio value="1">评价对象</a-radio>
                </a-radio-group>
              </a-form-item>
              <a-form-item v-show="(typeof(model.pid) === 'undefined' || model.pid === null) && dimensionType === '0'" :labelCol="labelCol" :wrapperCol="wrapperCol" label="评价周期">
                <j-dict-select-tag
                  type="list"
                  placeholder="请选择评价周期"
                  dictCode="dimension_date_type"
                  v-decorator="customDecorator('evalCycle', validatorRules.evalCycle)"
                  :trigger-change="true"
                  :disabled="!(typeof(model.pid) === 'undefined' || model.pid === null)" />
              </a-form-item>
              <a-form-item v-show="(typeof(model.pid) === 'undefined' || model.pid === null) && dimensionType === '1'" :labelCol="labelCol" :wrapperCol="wrapperCol" label="评价对象">
                <a-select
                  allowClear
                  placeholder="请选择评价对象"
                  style="width: 100%;"
                  v-decorator="customDecorator('evalObject', validatorRules.evalObject)"
                  :disabled="!(typeof(model.pid) === 'undefined' || model.pid === null)">
                  <a-select-option v-for="item in evalObjectData" :key="item.id" :value="item.id">{{ item.dimensionName }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-form>
            <div class="anty-form-btn">
              <a-button @click="emptyCurrForm" type="default" htmlType="button" icon="sync" :disabled="addFlag === 0">重置</a-button>
              <a-button @click="submitCurrForm" type="primary" htmlType="button" icon="form">保存</a-button>
            </div>
          </a-card>
          <a-card v-else>
            <a-empty>
              <span slot="description">请先选择一个评价分组!</span>
            </a-empty>
          </a-card>
        </a-tab-pane>
        <a-tab-pane tab="关联模型" key="2" :disabled="typeof(model.pid) === 'undefined' || model.pid === null">
          <EvaluationSystemRelateModelTableInfo v-show="selectedKeys.length > 0 && addFlag !== 1" ref="evaluationSystemRelateModelTableInfo" :evalId="model.id" />
          <a-card v-show="!selectedKeys.length > 0 || addFlag === 1">
            <a-empty>
              <span slot="description">{{ addFlag === 1 ? '请先创建评价分组!' : '请先选择一个评价分组!' }}</span>
            </a-empty>
          </a-card>
        </a-tab-pane>
      </a-tabs>
    </a-col>
  </a-row>
</template>

<script>
import pick from 'lodash.pick'
import { getAction, putAction, postAction, deleteAction } from '@/api/manage'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import EvaluationSystemRelateModelTableInfo from './modules/evaluationSystemRelateModelTableInfo'

export default {
  name: 'EvaluationSystem',
  components: { EvaluationSystemRelateModelTableInfo },
  mixins: [JeecgListMixin],
  data() {
    return {
      searchValue: '',
      dimensionType: '0',
      evalObjectData: [],
      replaceFields: {
        children: 'childList',
        title: 'name',
        key: 'id'
      },
      selectReplaceFields: {
        children: 'childList',
        title: 'name',
        key: 'id',
        value: 'id'
      },
      addFlag: 0, // 1新增
      activeKey: '1',
      iExpandedKeys: [],
      loading: false,
      autoExpandParent: true,
      currFlowId: '',
      currFlowName: '',
      disable: true,
      treeData: [],
      visible: false,
      rightClickSelectedKey: '',
      rightClickSelected: '',
      hiding: true,
      model: {},
      dropTrigger: '',
      depart: {},
      disableSubmit: false,
      checkedKeys: [],
      selectedKeys: [],
      autoIncr: 1,
      currSelected: {},
      allTreeKeys: [],
      checkStrictly: true,
      form: this.$form.createForm(this),
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      graphDatasource: {
        nodes: [],
        edges: []
      },
      validatorRules: {
        name: { rules: [{ required: true, message: '请输入分组名称!', pattern: '[^ \x22]+' }] },
        sysOrgCode: { rules: [{ required: true, message: '请输入分组编码!', pattern: '[^ \x22]+' }] },
        sort: { rules: [{ required: true, message: '请输入排序!' }] },
        status: { rules: [{ required: true, message: '请输入分组状态!' }] },
        evalCycle: { rules: [{ required: true, message: '请选择评价周期!' }] },
        evalObject: { rules: [{ required: true, message: '请选择评价对象!' }] }
      },
      url: {
        getevalObjectData: '/index/config/listDimension',
        list: '/eval/scSituationEval/queryTreeList',
        add: '/eval/scSituationEval/add',
        edit: '/eval/scSituationEval/edit',
        delete: '/eval/scSituationEval/delete',
        deleteBatch: '/eval/scSituationEval/deleteBatch'
      }
    }
  },
  created() {
    this.currFlowId = this.$route.params.id
    this.currFlowName = this.$route.params.name
    this.getDicData()
  },
  methods: {
    getDicData() {
      getAction(this.url.getevalObjectData, {}).then((res) => {
        if (res.success) this.evalObjectData = res.result
      })
    },
    loadData() {
      this.refresh()
    },
    loadTree() {
      var that = this
      var queryParam = {}
      queryParam.param = this.searchValue
      getAction(this.url.list, queryParam).then((res) => {
        if (res.success) {
          that.treeData = []
          // 部门全选后，再添加部门，选中数量增多
          this.allTreeKeys = []
          for (let i = 0; i < res.result.length; i++) {
            const temp = res.result[i]
            that.treeData.push(temp)
            that.setThisExpandedKeys(temp)
            that.getAllKeys(temp)
          }
        }
        if (res.code === 510) this.$message.warning(res.message)
      }).finally(() => {
        this.loading = false
      })
    },
    setThisExpandedKeys(node) {
      if (node.children && node.children.length > 0) {
        this.iExpandedKeys.push(node.key)
        for (let a = 0; a < node.children.length; a++) {
          this.setThisExpandedKeys(node.children[a])
        }
      }
    },
    refresh() {
      this.loading = true
      this.searchValue = ''
      this.loadTree()
    },
    // 右键操作方法
    rightHandle(node) {
      this.dropTrigger = 'contextmenu'
      this.rightClickSelectedKey = node.node.eventKey
      this.rightClickSelected = node.node.dataRef
    },
    onExpand(expandedKeys) {
      this.iExpandedKeys = expandedKeys
      this.autoExpandParent = false
    },
    backFlowList() {
      this.$router.back(-1)
    },
    // 右键点击下拉框改变事件
    dropStatus(visible) {
      if (visible === false) {
        this.dropTrigger = ''
      }
    },
    // 右键点击下拉关闭下拉框
    closeDrop() {
      this.dropTrigger = ''
    },
    addRootNode() {
      this.$refs.nodeModal.add(this.currFlowId, '')
    },
    batchDel: function() {
      if (this.checkedKeys.length <= 0) {
        this.$message.warning('请选择一条数据！')
      } else {
        var ids = ''
        for (var a = 0; a < this.checkedKeys.length; a++) {
          ids += this.checkedKeys[a] + ','
        }
        var that = this
        this.$confirm({
          title: '确认删除',
          content: '确定要删除所选中的 ' + this.checkedKeys.length + ' 条数据，以及子节点的数据吗?',
          onOk: function() {
            deleteAction(that.url.deleteBatch, { ids: ids }).then((res) => {
              if (res.success) {
                that.$message.success(res.message)
                that.checkedKeys = []
                that.loadTree()
                that.onClearSelected()
              } else {
                that.$message.warning(res.message)
              }
            })
          }
        })
      }
    },
    onSearch() {
      this.loadTree()
    },
    nodeModalOk() {
      this.loadTree()
    },
    hide() {
      this.visible = false
    },
    onCheck(checkedKeys, info) {
      this.hiding = false
      if (this.checkStrictly) {
        this.checkedKeys = checkedKeys.checked
      } else {
        this.checkedKeys = checkedKeys
      }
    },
    onSelect(selectedKeys, e) {
      this.hiding = false
      const record = e.node.dataRef
      this.currSelected = Object.assign({}, record)
      this.model = this.currSelected
      this.selectedKeys = [record.id]
      if (record.pid === '0') {
        record.pid = null
      }
      if (record.evalCycle) {
        this.dimensionType = '0'
      } else {
        this.dimensionType = '1'
      }
      this.model.pid = record.pid
      this.setValuesToForm(record)
      this.addFlag = 0
      this.activeKey = '1'
    },
    // 触发onSelect事件时,为部门树右侧的form表单赋值
    setValuesToForm(record) {
      this.$nextTick(() => {
        if (record.id === undefined || record.id === null) {
          this.form.resetFields()
          record.status = 1
        }
        record.status = Number(record.status) // 状态数据格式化
        if (record.evalObject === null) record.evalObject = undefined // 评价对象数据为空时重置
        record.status = Number(record.status)
        this.form.setFieldsValue(pick(record, 'name', 'sysOrgCode', 'sort', 'description', 'pid', 'status', 'evalCycle', 'evalObject'))
      })
    },
    getCurrSelectedTitle() {
      return !this.currSelected.name ? '' : this.currSelected.name
    },
    onClearSelected() {
      this.hiding = true
      this.currSelected = {}
      this.form.resetFields()
      this.selectedKeys = []
      if (this.addFlag === 1) this.addFlag = 0
    },
    handleNodeTypeChange(val) {
      this.currSelected.nodeType = val
    },
    notifyTriggerTypeChange(value) {
      this.currSelected.notifyTriggerType = value
    },
    receiptTriggerTypeChange(value) {
      this.currSelected.receiptTriggerType = value
    },
    submitCurrForm() {
      this.form.validateFields((err, values) => {
        if (!err) {
          if (this.addFlag === 1) {
            const formData = values
            !this.model.pid && this.dimensionType === '0' ? formData.evalObject = null : formData.evalCycle = null
            postAction(this.url.add, formData).then((res) => {
              if (res.success) {
                this.addFlag = 0
                this.$message.success('添加成功!')
                this.loadTree()
                this.onClearSelected()
              } else {
                this.$message.error(res.message)
              }
            })
          } else {
            const formData = Object.assign(this.currSelected, values)
            this.dimensionType === '0' ? formData.evalObject = null : formData.evalCycle = null
            putAction(this.url.edit, formData).then((res) => {
              if (res.success) {
                this.$message.success('保存成功!')
                this.loadTree()
              } else {
                this.$message.error(res.message)
              }
            })
          }
        }
      })
    },
    emptyCurrForm() {
      if (!this.addFlag) return
      this.form.resetFields()
    },
    openSelect() {
      this.$refs.sysDirectiveModal.show()
    },
    handleAdd(num) {
      if (num === 1) {
        this.activeKey = '1'
        this.addFlag = 1
        this.model.evalCycle = null
        this.model.evalObject = null
        this.model.pid = null
        this.setValuesToForm({})
      } else if (num === 2) {
        const key = this.currSelected.id
        if (!key) {
          this.$message.warning('请先点击选中上级分组！')
          return false
        }
        this.activeKey = '1'
        this.addFlag = 1
        this.model.evalCycle = this.currSelected.evalCycle
        this.model.evalObject = this.currSelected.evalObject
        this.model.pid = key
        this.setValuesToForm({ pid: key, evalCycle: this.currSelected.evalCycle, evalObject: this.currSelected.evalObject })
      } else {
        const key = this.rightClickSelectedKey
        if (!key) {
          this.$message.warning('请先点击选中上级分组！')
          return false
        }
        this.activeKey = '1'
        this.addFlag = 1
        this.model.evalCycle = this.rightClickSelected.evalCycle
        this.model.evalObject = this.rightClickSelected.evalObject
        this.model.pid = key
        this.setValuesToForm({ pid: key, evalCycle: this.currSelected.evalCycle, evalObject: this.currSelected.evalObject })
      }
    },
    handleDelete() {
      var that = this
      this.$confirm({
        title: '确认删除',
        content: '确定要删除此部门以及子节点数据吗?',
        onOk: function() {
          deleteAction(that.url.delete, { id: that.rightClickSelectedKey }).then((res) => {
            if (res.success) {
              that.checkedKeys.splice(that.checkedKeys.findIndex(key => key === that.rightClickSelectedKey), 1) // 删除成功后，去除已选中中的数据
              that.$message.success(res.message)
              that.loadTree()
              that.onClearSelected()
            } else {
              that.$message.warning(res.message)
            }
          })
        }
      })
    },
    selectDirectiveOk(record) {
      this.nodeSettingForm.setFieldsValue({ directiveCode: record.directiveCode })
      this.currSelected.sysCode = record.sysCode
    },
    getFlowGraphData(node) {
      this.graphDatasource.nodes.push({
        id: node.id,
        text: node.flowNodeName
      })
      if (node.children.length > 0) {
        for (let a = 0; a < node.children.length; a++) {
          const temp = node.children[a]
          this.graphDatasource.edges.push({
            source: node.id,
            target: temp.id
          })
          this.getFlowGraphData(temp)
        }
      }
    },
    expandAll() {
      this.iExpandedKeys = this.allTreeKeys
    },
    closeAll() {
      this.iExpandedKeys = []
    },
    checkAll() {
      this.checkStriccheckStrictlytly = false
      this.checkedKeys = this.allTreeKeys
    },
    cancelCheckAll() {
      this.checkedKeys = []
    },
    switchCheckStrictly(v) {
      if (v === 1) {
        this.checkStrictly = false
      } else if (v === 2) {
        this.checkStrictly = true
      }
    },
    getAllKeys(node) {
      this.allTreeKeys.push(node.id)
      if (node.childList && node.childList.length > 0) {
        for (let a = 0; a < node.childList.length; a++) {
          this.getAllKeys(node.childList[a])
        }
      }
    },
    dimensionTypeChange() {
      this.model.evalCycle || this.model.evalCycle === null ? this.form.setFieldsValue(pick(this.model, 'evalCycle')) : this.form.resetFields(['evalCycle'])
      this.model.evalObject ? this.form.setFieldsValue(pick(this.model, 'evalObject')) : this.form.resetFields(['evalObject'])
    },
    customDecorator(id, options) {
      if (!(typeof (this.model.pid) === 'undefined' || this.model.pid === null)) {
        options.rules[0].required = false
      } else {
        if (id === 'evalObject') options.rules[0].required = this.dimensionType === '1'
        if (id === 'evalCycle') options.rules[0].required = this.dimensionType === '0'
      }
      return [id, options]
    }
  }
}
</script>

<style scoped>
  .ant-card-body .table-operator {
    margin: 15px;
  }

  .anty-form-btn {
    width: 100%;
    text-align: center;
  }

  .anty-form-btn button {
    margin: 0 5px;
  }

  .anty-node-layout .ant-layout-header {
    padding-right: 0;
  }

  .header {
    padding: 0 8px;
  }

  .header button {
    margin: 0 3px;
  }

  .ant-modal-cust-warp {
    height: 100%;
  }

  .ant-modal-cust-warp .ant-modal-body {
    height: calc(100% - 110px) !important;
    overflow-y: auto;
  }

  .ant-modal-cust-warp .ant-modal-content {
    height: 90% !important;
    overflow-y: hidden;
  }

  #app .desktop {
    height: auto !important;
  }

  .ant-btn {
    margin-left: 3px;
  }

  .evaluation-system-tree {
    width: 100%;
    height: 460px;
    overflow: auto;
  }

  .drawer-bottom-button {
    bottom: 0;
    width: 100%;
    border-top: 1px solid #e8e8e8;
    padding: 10px 16px;
    text-align: left;
    left: 0;
    background: #fff;
    border-radius: 0 0 2px 2px;
  }
</style>
